from flask import request, jsonify, Blueprint, app, current_app

from app.persistence.HouseImage import HouseImage
from app.service import houseImageService
from app.util.jwtUtil import get_user_id_from_token
from app.enums import ErrorCode
from flask import Blueprint, jsonify, request
import oss2

house_image_bp = Blueprint('house_image', __name__)
# 复制upload_controller代码
# 阿里云 OSS 配置
OSS_ENDPOINT = 'oss-cn-beijing.aliyuncs.com'
OSS_BUCKET = 'izumi-yuu'
OSS_ACCESS_KEY_ID = 'LTAI5tC5tDanBxi8t73xdnvc'
OSS_ACCESS_KEY_SECRET = 'wrF7YBMQtKzaG2gE7a5nISVXBUIFeG'

def upload_to_oss(file):
    if file.filename == '':
        return None
    # 上传到阿里云 OSS
    auth = oss2.Auth(OSS_ACCESS_KEY_ID, OSS_ACCESS_KEY_SECRET)
    bucket = oss2.Bucket(auth, OSS_ENDPOINT, OSS_BUCKET)
    oss_path = f"uploads/{file.filename}"
    bucket.put_object(oss_path, file.stream)
    url = f"https://{OSS_BUCKET}.oss-cn-beijing.aliyuncs.com/{oss_path}"
    return url


@house_image_bp.route('/house-images', methods=['POST'])
def create_house_image():
    print("请求到达路由")
    print("Received files:", request.files)
    print("Received form data:", request.form)
    token = request.headers.get('Authorization')
    print(token)
    # user_id = get_user_id_from_token(token)
    user_id=token
    print(user_id)
    if not user_id:
        return jsonify({'code': ErrorCode.USER_TOKEN_INVALID.code,
                        'msg': ErrorCode.USER_TOKEN_INVALID.msg}), 401

    # 检查是否有文件上传
    if 'file' not in request.files:
        return jsonify({'code': ErrorCode.PARAM_MISSING.code,
                        'msg': '缺少图片文件'}), 400

    file = request.files['file']
    print("File object:", file)
    image_url = upload_to_oss(file)
    if not image_url:
        return jsonify({'code': ErrorCode.SERVER_ERROR.code,
                        'msg': '图片上传失败'}), 500

        # 从表单获取其他参数
    house_id = request.form.get('house_id')
    is_cover = request.form.get('is_cover', 'false').lower() == 'true'

    if not house_id:
        return jsonify({'code': ErrorCode.PARAM_MISSING.code,
                        'msg': '缺少house_id参数'}), 400

    image = houseImageService.create_house_image(
        house_id=house_id,
        image_url=image_url,
        is_cover=is_cover
    )

    if image:
        return jsonify({
            'code': ErrorCode.SUCCESS.code,
            'msg': '房屋图片添加成功',
            'data': {
                'image_id': image.imageid,
                'image_url': image.image_url,
                'is_cover': image.is_cover
            }
        }), 201
    else:
        return jsonify({'code': ErrorCode.SERVER_ERROR.code,
                        'msg': '房屋图片添加失败'}), 500

@house_image_bp.route('/house-images/<int:image_id>', methods=['GET'])
def get_house_image(image_id):
    image = houseImageService.get_image_by_id(image_id)
    if not image:
        return jsonify({'code': ErrorCode.IMAGE_NOT_FOUND.code,
                        'msg': '图片不存在'}), 404

    return jsonify({
        'code': ErrorCode.SUCCESS.code,
        'msg': '获取图片成功',
        'data': {
            'image_id': image.imageid,
            'house_id': image.houseid,
            'image_url': image.image_url,
            'is_cover': image.is_cover,
            'upload_time': image.upload_time.strftime('%Y-%m-%d %H:%M:%S') if image.upload_time else None
        }
    })


@house_image_bp.route('/house-images/house/<int:house_id>', methods=['GET'])
def get_house_images(house_id):
    images = houseImageService.get_images_by_house(house_id)
    images_data = [{
        'image_id': image.imageid,
        'image_url': image.image_url,
        'is_cover': image.is_cover,
        'upload_time': image.upload_time.strftime('%Y-%m-%d %H:%M:%S') if image.upload_time else None
    } for image in images]

    return jsonify({
        'code': ErrorCode.SUCCESS.code,
        'msg': '获取房屋图片列表成功',
        'data': images_data
    })


@house_image_bp.route('/house-images/<int:image_id>', methods=['PUT'])
def update_house_image(image_id):
    token = request.headers.get('Authorization')
    user_id = token
    if not user_id:
        return jsonify({'code': ErrorCode.USER_TOKEN_INVALID.code,
                        'msg': ErrorCode.USER_TOKEN_INVALID.msg}), 401

    allowed_updates = {}

    # 处理图片更新
    if 'file' in request.files:
        file = request.files['file']
        image_url = upload_to_oss(file)
        if image_url:
            allowed_updates['image_url'] = image_url
        else:
            return jsonify({'code': ErrorCode.SERVER_ERROR.code,
                            'msg': '图片上传失败'}), 500

    # 其他更新
    if 'is_cover' in request.form:
        allowed_updates['is_cover'] = request.form.get('is_cover').lower() == 'true'

    if not allowed_updates:
        return jsonify({'code': ErrorCode.PARAM_MISSING.code,
                        'msg': '没有提供可更新的字段'}), 400

    success = houseImageService.update_image(image_id, **allowed_updates)
    if success:
        return jsonify({'code': ErrorCode.SUCCESS.code,
                        'msg': '图片更新成功'})
    else:
        return jsonify({'code': ErrorCode.SERVER_ERROR.code,
                        'msg': '图片更新失败'}), 500




@house_image_bp.route('/house-images/<int:image_id>', methods=['DELETE'])
def delete_house_image(image_id):
    token = request.headers.get('Authorization')
    user_id = get_user_id_from_token(token)
    if not user_id:
        return jsonify({'code': ErrorCode.USER_TOKEN_INVALID.code,
                        'msg': ErrorCode.USER_TOKEN_INVALID.msg}), 401

    success = houseImageService.delete_image(image_id)
    if success:
        return jsonify({'code': ErrorCode.SUCCESS.code,
                        'msg': '图片删除成功'})
    else:
        return jsonify({'code': ErrorCode.SERVER_ERROR.code,
                        'msg': '图片删除失败'}), 500


@house_image_bp.route('/house-images/cover/<int:house_id>', methods=['GET'])
def get_house_cover_image(house_id):
    cover = houseImageService.get_cover_image(house_id)
    if not cover:
        return jsonify({'code': ErrorCode.IMAGE_NOT_FOUND.code,
                        'msg': '该房屋没有封面图片'}), 404

    return jsonify({
        'code': ErrorCode.SUCCESS.code,
        'msg': '获取封面图片成功',
        'data': {
            'image_id': cover.imageid,
            'image_url': cover.image_url,
            'upload_time': cover.upload_time.strftime('%Y-%m-%d %H:%M:%S') if cover.upload_time else None
        }
    })